<?php
/**
 * 基础控制器
 * @version 1.0
 * @author: HuangYu <992287102@qq.com>
 * @since: 2019/4/2 15:29
 * Class BaseController
 * @package app\index\controller
 */

namespace app\index\controller;

use think\Controller;

class BaseController extends Controller
{
    protected $page;      //页码
    protected $pageSize;  //每页条数

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();

        //初始化全局变量
        $this->initGlobal();
    }

    /**
     * 初始化全局变量
     * @return bool
     */
    private function initGlobal()
    {
        //页码获取
        $this->page     = (int)$this->request->param('page', 1);
        $this->pageSize = (int)$this->request->param('page_size', 10);
        if ($this->page < 1) {
            $this->page = 1;
        }
        if ($this->pageSize < 0) {
            $this->pageSize = 10;
        }

        return true;
    }

    /**
     * 分页信息统一格式
     * @param int $totalNum 数据总条数
     * @author: HuangYu
     * @date: 2019/1/16
     * @return array
     */
    protected function pagination($totalNum = 0)
    {
        return [
            'page'       => (int)$this->page,
            'page_size'  => (int)$this->pageSize,
            'total_num'  => (int)$totalNum,
            'total_page' => $this->pageSize > 0 ? ceil((int)$totalNum / $this->pageSize) : 1
        ];
    }

    /**
     * 生成排序数组
     * @param array $field 排序字段，
     * 如果传入字段与排序字段不同，可通过键和值映射，如：['money'=>'amount']
     * @author: HuangYu
     * @date: 2019/1/16
     * @return array
     */
    protected function getSort(array $field = [])
    {
        $sort = $this->request->param('sort');
        //参数解析
        if ($sort && is_string($sort)) {
            $sort = json_decode($sort, true);
        }
        $sort = $sort && is_array($sort) ? $sort : [];
        //字段映射
        foreach ($field as $k => $v) {
            if (!is_numeric($k) && isset($sort[$k])) {
                $sort[$v] = $sort[$k];
                unset($sort[$k]);
            }
        }
        //排序规则
        $orderBy = [];
        foreach ($sort as $key => $v) {
            if (in_array($key, $field) && $v) {
                $orderBy[$key] = $v == 'asc' ? 'asc' : 'desc';
            }
        }

        return $orderBy;
    }

    /**
     * 过滤空值、去除首位空格
     * @param array $param 数据
     * @param array $allowEmpty 允许为空字符串的字段
     * @return array
     */
    protected function arrayFilter($param = [], $allowEmpty = [])
    {
        $data = [];
        foreach ($param as $k => $v) {
            if (is_string($v)) {
                $v = trim($v);
            }
            if ($v === null) {
                continue;
            }
            if ($v === '' && !in_array($k, $allowEmpty)) {
                continue;
            }
            if (is_array($v)) {
                $v = $this->arrayFilter($v, $allowEmpty);
            }
            $data[$k] = $v;
        }

        return $data;
    }

    /**
     * 参数验证
     * @param string $model 验证器
     * @param string $scene 验证场景
     * @param array $param 数据
     * @return mixed
     */
    public function validator($model, $scene = '', $param = [])
    {
        if (strpos($model, 'Validate') === false) {
            $model .= 'Validate';
        }
        $validator = 'app\index\validate\\' . $model;
        if ($scene) {
            $validator .= '.' . $scene;
        }
        $result = $this->validate($param, $validator);
        if (true !== $result) {
            // 验证失败 输出错误信息
            return $result;
        } else {
            return '';
        }
    }

    /**
     * 数据返回统一格式
     * @param string $code 响应码
     * @param string $msg 提示信息
     * @param array $data 数据
     * @return \think\response\Json
     */
    protected function returnJson($code = '000', $msg = '', $data = [])
    {
        $arr['code'] = (string)$code;
        $arr['msg']  = $msg;
        $arr['data'] = $data;

        return json($arr);
    }
}